package cn.flexui.flexuiserver.controller.web;

import cn.dev33.satoken.stp.StpUtil;
import cn.flexui.flexuiserver.config.properties.FlexuiProperties;
import cn.flexui.flexuiserver.domain.entity.UserInfo;
import cn.flexui.flexuiserver.service.UserInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Map;

/**
 * @author wanmingyu
 * @create 2024/9/15 17:57
 */
@Tag(name = "登录")
@Controller
@RequestMapping("/oauth")
public class LoginController {

    @Autowired
    private Map<String, AuthRequest> authTypeMap;
    @Autowired
    private FlexuiProperties  flexuiProperties;
    @Autowired
    private UserInfoService userInfoService;

    @Operation(summary = "第三方登录")
    @Parameters({
            @Parameter(name = "authType", description = "登录类型 请查看字典文档"),
    })
    @GetMapping("/render/{authType}")
    public void renderAuth(@PathVariable String authType, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = authTypeMap.get(authType);
        String authorize = authRequest.authorize(AuthStateUtils.createState());
        response.sendRedirect(authorize);
    }

    @Operation(summary = "第三方登录回调")
    @RequestMapping("/callback/{authType}")
    public ModelAndView login(@PathVariable String authType, AuthCallback callback) {

        AuthRequest authRequest = authTypeMap.get(authType);
        AuthResponse<AuthUser> authResponse = authRequest.login(callback);
        if (authResponse.ok()) {
            // 三方登录成功
            UserInfo entity = doLogin(authType, authResponse);
            StpUtil.login(entity.getId());
        }

        return new ModelAndView("redirect:"+flexuiProperties.getDomain()+"/");
    }

    private UserInfo doLogin(String authType, AuthResponse<AuthUser> authResponse) {
        AuthUser authUser = authResponse.getData();
        String uuid = authUser.getUuid();

        UserInfo userInfo = userInfoService.selectByOpenId(uuid);
        if (userInfo != null) {
            return userInfo;
        }
        userInfo = new UserInfo();
        userInfo.setOpenId(uuid);
        userInfo.setNickname(authUser.getNickname());
        userInfo.setUsername(authUser.getUsername());
        userInfo.setRemark(authUser.getRemark());
        userInfo.setAvatar(authUser.getAvatar());
        userInfo.setEmail(authUser.getEmail());
        userInfo.setGender(authUser.getGender().getCode());
        userInfo.setAuthType(authType);
        userInfoService.save(userInfo);
        return userInfo;
    }
}
